package com.css.apps.base.user.action;

import cn.hutool.core.util.StrUtil;
import com.css.apps.base.common.Constants;
import com.css.apps.base.dict.service.DictMan;
import com.css.apps.base.org.model.SUserOrg;
import com.css.apps.base.security.model.SecurityParam;
import com.css.apps.base.security.service.SecurityService;
import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.po.UserFamilyPo;
import com.css.core.configuration.Environment;
import com.css.db.query.TransactionCache;
import com.css.util.*;
import com.opensymphony.xwork.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("serial")
public class ImportUser extends UserAction {

	private static Log log = LogFactory.getLog(ImportUser.class);

	private String orgId ;//导入的orgID
    private File file; //支持doc、docx 、zip（内含doc 或者 docx）三种格式的文件导入
    private final String tempUncompressPath = "/tempUserDocFile/";//临时解压缩文件夹路径

	protected String userGo() {
		try {
            //前置输入检查
            if(precheck(file)){
                return Action.ERROR;
            }
            //构建docfileArray
            long randomNum = System.currentTimeMillis();
            File[] fileArray = buildDocFileArray(file,randomNum);

            //逐个解析doc,入库
		    handleFiles(fileArray);

		    //清理解压的临时文件(zip情况)
            File uncompresTempFold = new File(tempUncompressPath+randomNum);
            if(uncompresTempFold.exists()){
                deleteDir(uncompresTempFold);
            }

            result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"));
			return Action.SUCCESS;
		} catch (Exception ex) {
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			return Action.ERROR;
		}
	}

    /**
     * 前置输入检查
     * @param file
     */
    private boolean precheck

     (File file) {
        if(file == null){
            result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
            return true;
        }
        if(!(file.getName().endsWith(".doc") || file.getName().endsWith(".docx") || file.getName().endsWith(".zip"))){
            result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.onlysuppotDocOrZip"));
            return true;
        }
        return false;
    }

    /**
     * 清理压缩产生的临时文件
     * @param fileArray
     */
    private void cleanFileArray(File[] fileArray) {
        try {
            if(fileArray!=null){
                for (File docfile : fileArray) {
                    docfile.delete();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 构建docFileArray
     * @param file
     * @return
     */
	private File[] buildDocFileArray(File file,long random){
        File[] fileArray = null;
        try {
            //根据文件格式判断是压缩包（zip格式）还是doc文件
            if(file.getName().endsWith(".zip")){
                //批量上传zip压缩包情况 解压 + 遍历
                fileArray = FileZipUtil.zipUncompressAndList(file,tempUncompressPath+random);
            }else {
                //直接上传单个doc文件
                fileArray = new File[1];
                fileArray[0] = file;
            }
        }catch (Exception e){
	        e.printStackTrace();
        }
        return  fileArray;
    }

    /**
     * 解析处理doc文件，入库
     * @param fileArray
     */
	private void handleFiles(File[] fileArray){
        TransactionCache tx = null;
        int totalnum = fileArray.length;
        int successnum = 0;
        int failnum=0;
        List<String> failFilepaths = new ArrayList<>(); //记录失败文件
        for (File file : fileArray) {
            try {
                //doc转table
                String[][] table2 = new WordUtil().getTableByword(file,2);
                String[][] table3 = new WordUtil().getTableByword(file,3);
                //printTable(table2,table3);
                //build suser、 userfamilyPo 、 sUserorg
                String userId = UuidUtil.getUuid();
                SUser userItem = buildUserItem(userId,table2,table3);
                List<UserFamilyPo> userFamilyPoList = buildUserFamilyPoList(userId,table3);
                SUserOrg userOrgItem = buildUserOrgItem(userId);
                tx = new TransactionCache();
                tx.save(userItem);
                tx.save(userFamilyPoList);
                tx.save(userOrgItem);
                tx.commit();
                successnum++;
            }catch (Exception e){
                if (tx != null) {
                    tx.rollback();
                }
                failnum++;
                failFilepaths.add(file.getAbsolutePath());
                continue;
            }
        }
        System.out.println("--------全部解析完毕----------");
        System.out.println("本此总共解析了 【 "+totalnum +" 】 个人员简历");
        System.out.println("本此成功导入了 【 "+successnum +" 】 个人员简历");
        for (String failFilepath : failFilepaths) {
            System.out.println(failFilepath+"文件解析失败！--------------------------");
        }
    }

    /**
     * 输出调试
     * @param table1
     * @param table2
     */
	private void printTable(String[][] table1, String[][] table2){
	    for (int i=0;i<table1.length;i++){
            for (int j=0;j<table1[i].length;j++){
                if(StrUtil.isNotEmpty(table1[i][j])){
                    System.out.println(table1[i][j]+"  =====对应坐标===>  "+"["+i+","+j+"]");
                }
            }
        }
        for (int i=0;i<table2.length;i++){
            for (int j=0;j<table2[i].length;j++){
                if(StrUtil.isNotEmpty(table2[i][j])){
                    System.out.println(table2[i][j]+"  =====对应坐标===>  "+"["+i+","+j+"]");
                }
            }
        }
    }

    /**
     * 构建Suser
     */
	private SUser buildUserItem(String userId, String[][] table1,String[][] table2){
        SUser item = new SUser();
        try {
            item.setUuid(userId);
            item.setRealName(table1[0][1]);
            String sex = DictMan.getDictCodeByName("d_sex",table1[0][3].trim());
            item.setSex(sex);
            item.setNation(table1[1][1]);
            item.setBirthday(strToDate(table1[0][5]));
            item.setNativeplace(table1[1][3]);
            item.setBirthplace(table1[1][5]);
            item.setJoinpartytime(strToDate(table1[2][1]));
            item.setJoinworktime(strToDate(table1[2][3]));
            item.setHealth(table1[2][5]);
            item.setProfessiontech_duty(table1[3][1]);
            item.setSkill(table1[3][3]);
            item.setFull_time_education(table1[4][2]);
            item.setFull_time_school_major(table1[4][4]);
            item.setOn_the_job_education(table1[6][2]);
            item.setOn_the_job_school_major(table1[6][4]);
            item.setCurrent_duty(table1[8][1]);
            item.setResume(TagReplace(table1[11][1]).trim());
            item.setReward_and_punish(TagReplace(table2[0][1]).trim());
            item.setExamine_conclusion(TagReplace(table2[1][1]).trim());
            item.setOrgId(orgId);
            item.setOpenFlag(Constants.YES);
            item.setDelFlag(Environment.UN_DELETE_STATE);
            item.setIssueDate(new Date());
            item.setIssueId(sUser.getUserId());
            item.setIssueName(sUser.getRealName());
            item.setEditDate(new Date());
            item.setTotalLoginCount(0);
            item.setFailedLoginCount(0);
            String password = SecurityService.getParamValue(SecurityParam.INIT_PASSWORD);
            if (StringHelper.isEmpty(password)) {
                item.setPassword(Md5Util.MD5Encode(Md5Util.MD5Encode("123456")));
            } else {
                item.setPassword(Md5Util.MD5Encode(Md5Util.MD5Encode(password)));
            }
            item.setActiveStatus("3");
            item.setFailedLoginCount(0);
            item.setLastmodifytime(new Date());
        }catch (Exception e){
            e.printStackTrace();
        }
        return item;
    }

    //构建家庭成员
    private List<UserFamilyPo> buildUserFamilyPoList(String userId, String[][] table) {
	    List<UserFamilyPo> userFamilyPoList  = new ArrayList<>();
        for(int i=4; i<11; i++){
            //过滤掉空行人员
            boolean createFlag = false;
            for (int j=1;j<6;j++){
                if(StringHelper.isNotEmpty(table[i][j])){
                    createFlag = true;
                    break;
                }
            }
            if(createFlag){
                UserFamilyPo userFamilyPo = new UserFamilyPo();
                userFamilyPo.setUuid(UuidUtil.getUuid());
                userFamilyPo.setUserId(userId);
                userFamilyPo.setAppellation(table[i][1]);
                userFamilyPo.setMembername(table[i][2]);
                userFamilyPo.setBirthday(table[i][3]);
                userFamilyPo.setPoliticallandscape(table[i][4]);
                userFamilyPo.setUnitandposition(table[i][5]);
                userFamilyPoList.add(userFamilyPo);
            }
        }
	    return userFamilyPoList;
    }

    /**
     * 构建SuserOrg关联信息
     * @param userId
     * @return
     */
    private SUserOrg buildUserOrgItem(String userId) {
        SUserOrg sUserOrg = new SUserOrg();
        sUserOrg.setOrgId(orgId);
        sUserOrg.setDeptId(orgId);
        sUserOrg.setUserId(userId);
        return  sUserOrg;
    }

    private Date strToDate(String dateStr) throws ParseException {
        return StringHelper.isEmpty(dateStr) ? null : new SimpleDateFormat("yyyy.MM").parse(dateStr);
    }

    private Date strToBirth(String dateStr) throws ParseException {
        return StringHelper.isEmpty(dateStr) ? null : new SimpleDateFormat("yyyy.MM.dd").parse(dateStr);
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    //特殊字符转义
    private String TagReplace(String sSource) {
        if (StringHelper.isEmpty(sSource)) {
            return "";
        } else {
            Pattern p = null;
            Matcher m = null;
            String s = null;
            String sTmp = null;
            StringBuffer sb = null;
            p = Pattern.compile("(\\n|\\r|<|>)", 2);
            m = p.matcher(sSource);

            for(sb = new StringBuffer(); m.find(); m.appendReplacement(sb, s)) {
                sTmp = m.group().toLowerCase();
                if (sTmp.equals("\n")) {
                    s = "<br/>";
                } else if (sTmp.equals("\r")) {
                    s = "";
                } else if (sTmp.equals("<")) {
                    s = "&lt;";
                } else if (sTmp.equals(">")) {
                    s = "&gt;";
                }
            }
            m.appendTail(sb);
            return sb.toString().replace("<br/> ","<br/>");
        }
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getOrgId() {
        return orgId;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }
}
